package net.amsoft.iservice.isso.webapp.struts.action;

import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.amsoft.iservice.isso.service.ISSOService;
import net.amsoft.iservice.isso.util.ISSOConstants;
import net.amsoft.iservice.isso.webapp.dataObject.LoginData;
import net.amsoft.iservice.util.IServiceUtil;
import net.amsoft.iservice.util.ResolverClient;
import static net.amsoft.iservice.isso.util.ISSOConstants.*;
import static net.amsoft.iservice.util.IServiceConstants.PARAM_SERVICE_ACTIVE;
import static net.amsoft.iservice.util.IServiceConstants.RESPONSE_URI;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CheckLogin extends BaseAction {

    private static final Logger oLogger = Logger.getLogger(CheckLogin.class);

    @Override
    public ActionForward process(ActionMapping oMapping, ActionForm oForm,
            HttpServletRequest oRequest, HttpServletResponse oResponse)
            throws Exception {
        oLogger.info("process(): entry");

        String sXri = oRequest.getParameter("xri");
        if (sXri != null) {

            /*
             * Normalize requested XRI
             */
            sXri = sXri.replaceAll("\\s", "+");
            String sIname = null;
            try {
                sIname = IServiceUtil.getIName(sXri);
                if (sIname == null)
                    throw new Exception("Invalid XRI");
                else
                    sIname = sIname.toLowerCase();
            } catch (Exception e) {
                oLogger.warn("process() invalid xri:" + sXri);
                oResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // HTTP
                                                                        // 404
                return new ActionForward();
            }

            /*
             * CHECK IF THE SERVICE IS ACTIVE OR NOT for the given synonym and
             * respond
             */
            String sAcceptHeader = oRequest.getParameter(PARAM_SERVICE_ACTIVE);
            if (sAcceptHeader != null && sAcceptHeader.equals("true")) {
                String sGINU = ResolverClient.getGlobalINumber(sIname);
                boolean bIsSubscribed = ISSOService.verifySynonym(sGINU,
                        sIname, oRequest.getServerName());
                if (bIsSubscribed) {
                    oResponse.setStatus(HttpServletResponse.SC_OK); // HTTP 200

                    // Write response back to client
                    oResponse.setContentType(RESPONSE_URI);
                    PrintWriter out = oResponse.getWriter();
                    out.println("https://" + oRequest.getServerName()
                            + "/isso/PreLogin?synonym=" + sIname);
                    out.flush();
                    out.close();
                } else {
                    oResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // HTTP
                    // 404
                }

                return new ActionForward();
            }
        }

        LoginData oLoginData = (LoginData) oRequest.getSession(false)
                .getAttribute(SESSION_LOGIN_OBJ);
        if (oLoginData.isLoginStatus() && oLoginData.getSessionCookie() != null) {
            oLogger.info("process(): forward to welcome page");
            oLogger.info("process(): SessionCookie="
                    + oLoginData.getSessionCookie());
            String sBrokerName = oRequest.getServerName();
            String sSpXri = ISSOConstants.getSPXri(sBrokerName);
            oRequest.setAttribute(ISSOConstants.REQ_PARAM_SPXRI, sSpXri);
            String sSessionCookie = null;
            Cookie[] oCookie = oRequest.getCookies();
            if (oCookie != null) {
                for (int i = 0; i < oCookie.length; i++) {
                    if (oCookie[i].getName().equals(SESSION_COOKIE_NAME)) {
                        sSessionCookie = oCookie[i].getValue();
                    }// IF
                }// FOR
            }
            oLogger.info("process(): sSessionCookie=" + sSessionCookie);
            return oMapping.findForward(SUCCESS_FWD);
        } else {
            oLogger.error("process() : forward to iname page"
                    + ", LoginStatus=" + oLoginData.isLoginStatus()
                    + ", SessionCookie=" + oLoginData.getSessionCookie());
            oLoginData.setLoginStatus(false);
            return oMapping.findForward(FAILURE_FWD);
        }
    }
}
